package com.dao.impl;

import java.net.URLDecoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.dao.AccountDao;
import com.domain.Account;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

	private static final Logger log = LoggerFactory
			.getLogger(AccountDaoImpl.class);

	public List<Account> getListAccount(int begin, int limit) {
		StringBuilder sql = new StringBuilder();
		sql.append("Select * from Account ORDER BY id ASC LIMIT ?, ?");

		log.debug(sql.toString());

		return getJdbcTemplate().query(sql.toString(), new Object[]{begin,limit},
				new RowMapper<Account>() {
					@SuppressWarnings("deprecation")
					public Account mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Account account = new Account();

						account.setId(rs.getInt("id"));
						account.setUsername(new String(Base64.decodeBase64(rs.getString("username"))));
						account.setUsernameUrlDecode(URLDecoder.decode(new String(Base64.decodeBase64(rs.getString("username")))));
						account.setPassword(new String(Base64.decodeBase64(rs.getString("password"))));
						account.setEmail(rs.getString("email"));

						return account;
					}
				});
	}

	public Account findAccountById(int id) {
		return null;
	}

	public Account findAccountByUsername(String username) {
		// TODO Auto-generated method stub
		return null;
	}

	public Account findAccountByEmail(String email) {
		// TODO Auto-generated method stub
		return null;
	}

	public void deleteAccount(int id) {
		StringBuilder sql = new StringBuilder();
		sql.append("delete from Account WHERE id = ?");

		log.debug(sql.toString());
		
		getJdbcTemplate().update(sql.toString(), id);
	}

	public void updateAccount(Account acc) {
		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE ACCOUNT SET username = ?, password = ?, email = ? WHERE id = ?");

		log.debug(sql.toString());
		
		getJdbcTemplate().update(sql.toString(), acc.getUsername(), acc.getPassword(), acc.getEmail(), acc.getId());
	}

	public void createAccount(Account acc) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO ACCOUNT(username, password, email) value (?, ?, ?)");

		log.debug(sql.toString());
		
		getJdbcTemplate().update(sql.toString(), acc.getUsername(), acc.getPassword(), acc.getEmail());
	}

	public int getTotalAccount() {
		StringBuilder sql = new StringBuilder();
		sql.append("Select count(id) from Account");

		log.debug(sql.toString());

		return getJdbcTemplate().queryForInt(sql.toString());
	}

}
